package cn.stu.system.controller;


import cn.stu.common.utils.ApiData;
import cn.stu.common.utils.UserHolder;
import cn.stu.framework.dto.LoginDto;
import cn.stu.framework.entity.Users;
import cn.stu.framework.service.LoginLogService;
import cn.stu.framework.service.UsersService;
import cn.stu.system.annotation.LogAnnotation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户控制器
 *
 * @author HGZS
 * @date 2023/08/03
 * @menu 用户管理
 */
@RestController
@RequestMapping("/users")
@AllArgsConstructor
public class UsersController {

    private final UsersService usersService;

    private final LoginLogService loginLogService;

    /**
     * 登录
     *
     * @param users   用户
     * @param request 请求
     * @return {@link ApiData}
     */
    @PostMapping(value = "/login")
    public ApiData login(@RequestBody @Valid LoginDto users, HttpServletRequest request) {
        ApiData login = usersService.login(users, request);
        loginLogService.addLog(request, users, login);
        return login;
    }



    /**
     * 设置角色
     *
     * @param userId 用户id
     * @param roleId 角色id
     * @return {@link ApiData}
     */
    @LogAnnotation("设置用户角色")
    @PutMapping(value = "/setRole")
    public ApiData setRole(@RequestParam("userId") Long userId, @RequestParam("roleId") Long roleId) {
        return usersService.setRole(userId, roleId);
    }

    /**
     * 获取路由
     *
     * @return {@link ApiData}
     */
    @GetMapping(value = "/getRoutes")
    public ApiData getRoutes() {
        Long userId = UserHolder.getUser().getUserId();
        Users users = usersService.getById(userId);
        if (users == null) {
            return ApiData.getFalse("用户id异常");
        }
        if (users.getRoleId() == null) {
            return ApiData.getTrue("success", null);
        }
        return usersService.getRoutes(users.getRoleId());
    }

    /**
     * 注销
     *
     * @param request 请求
     * @return {@link ApiData}
     */
    @GetMapping(value = "/logout")
    public ApiData logout(HttpServletRequest request) {
        return usersService.logout(request);
    }
}

